package com.luo.partner.controller;

import com.luo.common.controller.BaseController;
import com.luo.common.utils.R;
import com.luo.system.domain.UserDO;
import com.luo.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

@Controller
@RequestMapping("/partner/applyCommission")
public class ApplyCommissionController extends BaseController{

	@Autowired
	UserService userService;

    @GetMapping()
    @RequiresPermissions("applyCommission")
    String tabUsrs(Model model) {
    	model.addAttribute("user", userService.get(getUserId()));
        return "partner/applyCommission/commission";
    }


    /**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/apply")
    @RequiresPermissions("applyCommission")
    public R apply(Long userId,String commission) {
		UserDO userDO = getUser();
		if (userDO.getLevel() != 2) {
			return R.error("没权限申请提现");
		}
		BigDecimal c = null;
		try {
			c = new BigDecimal(commission);
			if (c.compareTo(userDO.getUnWithdrawCommission()) > 0) {
				return R.error("申请提现金额超过可提现的金额");
			}
			if (c.compareTo(new BigDecimal(0)) <= 0) {
				return R.error("申请提现金额应大于0");
			}
			c = c.setScale(2, BigDecimal.ROUND_HALF_UP);
		} catch (Exception e) {
			return R.error("申请提现金额输入有误");
		}
		
        try {
        	userService.applyCommission(c, userDO);
        	return R.ok();
		} catch (RuntimeException e) {
			return R.error("提现失败，" + e.getMessage());
		}
	}
	
}
